package demo.java.lang.management.vo;

import org.apache.log4j.RollingFileAppender;
import org.apache.log4j.spi.LoggingEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.atomic.AtomicLong;


/**
 * @author mandy.hu
 *
 */
public class TimedBufferedRollingFileAppender extends RollingFileAppender {
	
    private static final Logger logger = LoggerFactory.getLogger(TimedBufferedRollingFileAppender.class);
    
    private static final Object appendersLock = new Object();
    
    private volatile AtomicLong count = new AtomicLong();
    private volatile Long lastTime = System.currentTimeMillis();

    public TimedBufferedRollingFileAppender(){
        super();
    }

    private void flush() {
    	try {
    		if (!checkEntryConditions()) return;
            qw.flush();
		} catch (Exception e){
			logger.error("TimedBufferedRollingFileAppender flush error",e);
		}
        
    }
    @Override
	public void append(LoggingEvent event){
    	super.append(event);
    	long n = count.incrementAndGet();
		if (System.currentTimeMillis() - lastTime >= 20000) {
			if (n < 500) {
				synchronized (appendersLock) {
					if (System.currentTimeMillis() - lastTime >= 20000) {
						flush();
					}
				}
			}
			count.getAndSet(0);
			lastTime = System.currentTimeMillis();
		}
    }
}